<template>
  <div>
    <a-form ref='form' v-model='formData'>
      <a-row>
        <a-col :span='8'>
          <a-form-item label='显示设置' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-radio-group v-model='formData.set'>
              <a-radio :value='0'>显示</a-radio>
              <a-radio :value='1'>隐藏</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span='8'>
          <a-form-item label='显示菜单' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-radio-group v-model='formData.menu'>
              <a-radio :value='0'>显示</a-radio>
              <a-radio :value='1'>隐藏</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span='8'>
            <a-form-item label='页面模式' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-radio-group v-model='formData.mode'>
                <a-radio :value='0'>多页</a-radio>
                <a-radio :value='1'>单页</a-radio>
              </a-radio-group>
            </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='8'>
          <a-form-item label='节点遮罩层' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-radio-group v-model='formData.mask'>
              <a-radio :value='0'>显示</a-radio>
              <a-radio :value='1'>隐藏</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span='8'>
          <a-form-item label='播放方式' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-radio-group v-model='formData.playType'>
              <a-radio :value='0'>背景音乐</a-radio>
              <a-radio :value='1'>节点连播</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span='8' v-show='formData.playType === 0'>
          <a-button type='primary' @click='handleSelectAudio'>选项背景音乐</a-button>
          <span style='display: inline-block;margin-left: 15px;'>{{ formData.fileName }}</span>
        </a-col>
      </a-row>
<!--      <el-row>-->
<!--      <a-col :span='8'>-->
<!--        <a-form-item label='显示缩略图' :labelCol='labelCol' :wrapperCol='wrapperCol'>-->
<!--          <a-radio-group v-model='formData.thumb'>-->
<!--            <a-radio :value='0'>显示</a-radio>-->
<!--            <a-radio :value='1'>隐藏</a-radio>-->
<!--          </a-radio-group>-->
<!--        </a-form-item>-->
<!--      </a-col>-->
<!--      </el-row>-->
    </a-form>
    <a-row>
      <a-col :span='6'>
        <a-card>
          <h4>页面列表:</h4>
          <div class='page-list page-scroll'>
            <draggable
              v-if='pages.length'
              v-model='pages'
              @start='drag=true'
              @end='drag=false'
            >
              <div @click='changePage(idx)' class='page-item flex' :class="currentPageId === idx?'active':''"
                   v-for='(item,idx) in pages' :key="idx+''">
                <a-tooltip placement="topLeft" title="点击更换">
                <div class='img' @click.stop='handleChangeImage(idx)'>
                  <div v-if='item.imageUrl' class='img-cover' :style="{ backgroundImage: `url('${item.imageUrl}')` }"></div>
                  <a-icon v-else type='plus'></a-icon>
                </div>
                </a-tooltip>
                <div>
                  <a-input placeholder='页面名标题' v-model='item.name' @focus='changePage(idx)'></a-input>
                  <p class='oneline-hide'>{{item.fileName}}</p>
                  <div>
                    <a-tag
                      v-if='item.id'
                      class='cur-p'
                      :color="item.status === 10 ? 'green' : 'red'"
                      @click='item.status= item.status ===10?20:10'
                    >{{ item.status === 10 ? '正常' : '停用' }}
                    </a-tag>
                    <a-button v-else type='danger' size='small' @click.stop='delPage(idx)'>删除</a-button>
                  </div>
                </div>
              </div>
            </draggable>
          </div>
          <div>
            <a-button @click='handleSelectImage' class='btn-add'>+</a-button>
          </div>
        </a-card>
      </a-col>
      <a-col :span='12'>
        <a-card class='card-cropper'>
          <div class='page-cropper'>
            <vueCropper
              ref='cropper'
              :canScale='false'
              :canMove='false'
              :original='false'
              :centerBox='true'
              :autoCropWidth='cropW'
              :autoCropHeight='cropH'
              mode='100% auto'
              @imgLoad='cropperImgLoad'
              :img='currentImg'
            ></vueCropper>
          </div>
        </a-card>
      </a-col>
      <a-col :span='6'>
        <a-card>
          <h3>{{ pages[currentPageId] ? pages[currentPageId].name : '' }}</h3>
          <h4 :style='{color:formData.playType ===0?"#ccc":""}'>区域列表</h4>
          <div class='page-list area-scroll' v-show='cropperImgLoadSuccess && formData.playType === 1'>
            <draggable
              v-if='nodes.length'
              v-model='nodes'
              @start='drag=true'
              @end='drag=false'
              @update='onUpdateNodeChange'
            >
            <div class='page-item' :class="currentNodeId === idx?'active':''"
                 v-for='(node,idx) in nodes' @click='changeNode(idx)'>
              <!--              <a-icon-->
              <!--                class="icon-close"-->
              <!--                theme="filled"-->
              <!--                type="close-circle"-->
              <!--              />-->
              <a-tooltip placement="topLeft" title="点击更换">
              <div @click.stop='handleChangeVideo(idx)'>区域{{ idx + 1 }}: <span>{{ node.fileName }}</span></div>
              </a-tooltip>
              <div class='node-crop'>
                <div class='node-crop-box' :style='node.cropBoxStyle'>
                  <img :src='pages[currentPageId]?pages[currentPageId].imageUrl:""' :style='node.cropImgStyle' />
                </div>
              </div>
              <div>
                <a-button type='danger' size='small' @click.stop='delNode(idx)'>删除</a-button>
                <a-button  @click='editCrop(node,idx)' size='small'>修改截图</a-button>
                <a-button type='primary' @click='saveCrop(node)' v-show='cropping && currentNodeId === idx'
                          size='small'>保存截图
                </a-button>
              </div>
            </div>
            </draggable>
          </div>
          <div v-show='cropperImgLoadSuccess && formData.playType === 1' style='text-align: center;'>
            <a-button @click='handleSelectVideo' class='btn-add'>+</a-button>
            <a-radio-group v-model:value="nodeCoverType" button-style="solid" style='margin-top: 10px;'>
              <a-radio-button :value="true">节点自定义</a-radio-button>
              <a-radio-button :value="false">页面全覆盖</a-radio-button>
            </a-radio-group>

          </div>
        </a-card>
      </a-col>
    </a-row>
    <!-- 文件选择器 -->
    <BookFilesModel
      ref='BookFilesModal'
      :multiple='multiple'
      @handleSubmit='handleSelectVideoSubmit'
    />
    <FilesModal
      ref='FilesModal'
      showGroupBtn
      :multiple='multiple'
      @handleSubmit='handleSelectImageSubmit'
    />
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
import draggable from 'vuedraggable'
import { BookFilesModel, FilesModal } from '@/components/Modal'
import cloneDeep from 'lodash.clonedeep'

const pageInfoDef = {
  name: '',
  imageUrl: '',
  imageId: '',
  fileName:'',
  width: 0,
  nodes: []
}
const nodeInfoDef = {
  fileId: '',
  fileName: '',
  x1: 0, x2: 0, y1: 0, y2: 0,
  cropBoxStyle: {},
  cropImgStyle: {}
}
export default {
  name: 'imageNode',
  components: {
    VueCropper,
    draggable, BookFilesModel, FilesModal
  },
  data() {
    return {
      bookName: '',
      pages: [],
      nodes:[],
      nodeCoverType:true,
      formData: {
        mode:0,set: 0, menu: 0,  mask: 1, playType: 1, audioId: '', fileName: ''
      },
      cropW:50,
      cropH:50,
      // 标签布局属性
      labelCol: { span: 7 },
      // 输入框布局属性
      wrapperCol: {
        span: 13
      },
      multiple:true,
      playing: false,
      cropping: false,
      currentPageId: 0,
      currentImg: '',
      currentNodeId: 0,
      cropperImgLoadSuccess: false,
      changeImgIdx:-1,
      changeNodeIdx:-1,
      mediaType:0,
    }
  },
  //模块
  methods: {
    num2zh(num) {
      if (num < 0 || num > 9999) {
        return ''
      }
      var arr1 = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
      var arr2 = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿']//可继续追加更高位转换值
      if (!num || isNaN(num)) {
        return '零'
      }
      var english = num.toString().split('')
      var result = ''
      for (var i = 0; i < english.length; i++) {
        var des_i = english.length - 1 - i//倒序排列设值
        result = arr2[i] + result
        var arr1_index = english[des_i]
        result = arr1[arr1_index] + result
      }
      return result.replace(/零(千|百|十)/g, '零')
        .replace(/十零/g, '十')
        .replace(/零+/g, '零')
        .replace(/零亿/g, '亿').replace(/零万/g, '万')
        .replace(/亿万/g, '亿')
        .replace(/零+$/, '')
        .replace(/^一十/g, '十')
    },

    handleSortFilename(list){
      list.sort((a,b)=>{
        let reg = /^[A-z\d]/
        if(reg.test(a.fileName) || reg.test(b.fileName)){
          if(a.fileName > b.fileName){
            return 1;
          }else if(a.fileName < b.fileName){
            return -1;
          }
          return 0;
        }else{
          return a.fileName.localeCompare(b.fileName,'zh')
        }
      })
      return list
    },
    setFormData(data,pageId) {
      if(data.form) this.formData = data.form
      this.pages = data.pages
      this.changePage(0)
    },
    getFormData() {
      return new Promise((resolve) => {
        if (this.formData.playType === 0 && !this.formData.audioId) {
          this.$message.error('请选择背景音乐')
          return
        }
        if (!this.pages.length) {
          this.$message.error('请添加页面')
          return
        }
        resolve({
          form: this.formData,
          pages: this.pages
        })
      })
    },

    //删除页面
    delPage(idx) {
      this.pages.splice(idx, 1)
      this.changePage(this.pages.length - 1)
    },
    //切换页面
    changePage(id) {
      this.currentPageId = id
      this.currentNodeId = 0
      if (!(this.pages[id] ? this.pages[id].imageUrl : '')) {
        this.cropperImgLoadSuccess = false
        this.currentImg = ''
        this.$refs.cropper.refresh()
      } else {
        if (this.currentImg !== this.pages[id].imageUrl) {
          this.currentImg = this.pages[id].imageUrl
        }
      }
      this.nodes = this.pages[id]?this.pages[id].nodes:[];
      this.cropping = false
    },
    onUpdateNodeChange(){
      this.pages[this.currentPageId].nodes=this.nodes
    },
    handleChangeImage(idx){
      this.multiple=false
      this.changeImgIdx = idx
      this.$refs.FilesModal.show()
    },
    // 打开文件选择器
    handleSelectImage() {
      this.multiple=true
      this.changeImgIdx = -1
      this.$refs.FilesModal.show()
    },

    // 文件库modal确认回调
    handleSelectImageSubmit(result) {
      if(this.changeImgIdx > -1){
        //单一修改
        this.pages[this.changeImgIdx].imageUrl =  result[0].preview_url
        this.pages[this.changeImgIdx].imageId =  result[0].file_id
        this.pages[this.changeImgIdx].fileName =  result[0].file_name
        this.pages[this.changeImgIdx].width =   result[0].file_info?result[0].file_info.width:0
        this.changePage(this.changeImgIdx)
      }else{
        //批量添加
        let len = this.pages.length;
        result.forEach(row => {
          len++
          const item = cloneDeep(pageInfoDef)
          item.imageUrl = row.preview_url
          item.imageId = row.file_id
          item.fileName = row.file_name
          item.width = row.file_info?row.file_info.width:0
          item.name = row.file_name.split('.')[0]
          this.pages.push(item)
        })
        this.handleSortFilename(this.pages)
        // this.pages.forEach((row,idx)=>{
        //   row.name = /第.+页/.test(row.name)|| !row.name?'第'+this.num2zh(idx+1)+'页':row.name
        // })
        this.changePage(len-1)
        setTimeout(() => {
          let p = document.querySelector('.page-scroll')
          p.scrollTop = p.querySelector('.page-item:last-child').offsetTop
        }, 300)
      }

    },
    handleSelectAudio() {
      this.mediaType = 1
      this.multiple=false
      this.$refs.BookFilesModal.show()
    },
    handleChangeVideo(idx){
      this.changeNodeIdx = idx
      this.mediaType = 0
      this.multiple=false
      this.$refs.BookFilesModal.show()
    },
    handleSelectVideo() {
      if (this.cropperImgLoadSuccess) {
        this.multiple=true
        this.mediaType = 0
        this.$refs.BookFilesModal.show()
      } else {
        this.$message.error('请选择图片')
      }
    },
    handleSelectVideoSubmit(result) {
      this.$refs.cropper.clearCrop()
      if(this.mediaType === 1 ){
        this.handleSelectAudioSubmit(result)
      }else if(this.changeNodeIdx > -1){
        this.currentNodeId = this.changeNodeIdx
        this.nodes[this.changeNodeIdx].fileId = result[0].id
        this.nodes[this.changeNodeIdx].fileName = result[0].full_name
      }else{
        result.forEach(row => {
          const item = cloneDeep(nodeInfoDef)
          item.fileId = row.id
          item.fileName = row.full_name
          this.nodes.push(item)
        })
        this.handleSortFilename(this.nodes)
        this.currentNodeId = this.nodes.length - 1
        if(this.nodeCoverType){
          this.cropW=50
          this.cropH=50
        }else{
          this.cropH=this.$refs.cropper.trueHeight
          this.cropW=this.$refs.cropper.trueWidth
        }
        setTimeout(()=>{
          this.$refs.cropper.goAutoCrop()
          this.cropping = true
          if(!this.nodeCoverType){
            this.saveCrop(this.nodes[this.currentNodeId])
          }
        },150)
      }
    },

    handleSelectAudioSubmit(result) {
      if (!/mp3+$/.test(result[0].full_name)) {
        this.$message.error('请选择音频文件')
        return
      }
      this.formData.fileName = result[0].full_name
      this.formData.audioId = result[0].id
    },

    //图片处理区域图片加载成功
    cropperImgLoad(e) {
      this.cropping = false
      if (e === 'success' && (this.pages[this.currentPageId] ? this.pages[this.currentPageId].imageUrl : '')) {
        if(this.pages[this.currentPageId].nodes.length){
          if(!this.pages[this.currentPageId].nodes[0].hasOwnProperty('cropBoxStyle')){
            const rate = this.$refs.cropper.scale
            this.pages[this.currentPageId].nodes.forEach(node=>{
              node.cropImgStyle =this.getCropImgStyle(node,rate)
              node.cropBoxStyle = this.getCropBoxStyle(node,rate)
            })
          }
        }

        this.pages[this.currentPageId].width = this.$refs.cropper.trueWidth
        this.cropperImgLoadSuccess = true
      }
    },
    getCropBoxStyle(node, rate) {
      let trueWidth = (node.x2 - node.x1) * rate
      let trueHeight = (node.y2 - node.y1) * rate
      let w = 200, h = 100
      let scale = w / trueWidth
      if (trueHeight >= h || (trueHeight * scale) > 100) {
        scale = h / trueHeight
      }
      let x =
        -(trueWidth - trueWidth * scale) / 2 +
        (w - trueWidth * scale) / 2

      let y =
        -(trueHeight - trueHeight * scale) / 2 +
        (h - trueHeight * scale) / 2
      let transformX = x / scale
      let transformY = y / scale
      return {
        width: trueWidth + 'px',
        height: trueHeight + 'px',
        transform: 'scale(' + scale + ')translate(' + transformX + 'px, ' + transformY + 'px) ' //
      }
    },
    getCropImgStyle(node, rate) {
      return {
        top: '-' + (node.y1 * rate) + 'px',
        left: '-' + (node.x1 * rate) + 'px'
      }
    },
    //保存截图
    saveCrop(node) {
      let rate = this.$refs.cropper.scale
      let top = (800 - this.$refs.cropper.trueHeight * rate) / 2
      node.x1 = this.parseFloat((this.$refs.cropper.getCropAxis().x1) / rate)
      node.x2 = this.parseFloat((this.$refs.cropper.getCropAxis().x2) / rate)
      node.y1 = this.parseFloat((this.$refs.cropper.getCropAxis().y1 - top) / rate)
      node.y2 = this.parseFloat((this.$refs.cropper.getCropAxis().y2 - top) / rate)
      node.cropImgStyle = this.getCropImgStyle(node, rate)
      node.cropBoxStyle = this.getCropBoxStyle(node, rate)
      this.$refs.cropper.clearCrop()
      this.cropping = false
    },
    parseFloat(num){
      return parseFloat(num.toFixed(2))
    },
    getNodeStyle(node){
      let rate = this.$refs.cropper.scale
      node.cropImgStyle = this.getCropImgStyle(node, rate)
      node.cropBoxStyle = this.getCropBoxStyle(node, rate)
    },
    //修改截图
    editCrop(idx) {
      this.$refs.cropper.goAutoCrop()
      this.cropping = true
      this.currentNodeId = idx
    },
    //删除区域
    delNode(idx) {
      this.pages[this.currentPageId].nodes.splice(idx, 1)
      this.currentNodeId = this.pages[this.currentPageId].nodes.length - 1
    },
    changeNode(idx) {
      this.currentNodeId = idx
    }
  }
}
</script>

<style lang='less' scoped>
.btn-add {
  width: 100%;
  margin-top: 10px;
  font-size: 24px;
  height: 40px;
}

.page-list {
  max-height: 500px;
  overflow: scroll;
  padding: 10px 10px 10px 0;

  .page-item {
    padding-top: 10px;
    cursor: pointer;
    border-bottom: 1px dashed #ccc;
    margin-bottom: 10px;
    padding-bottom: 10px;
    position: relative;

    &.flex {
      display: flex;
    }

    &.active {
      border-left: 3px solid blue;
    }

    &:hover {
      .icon-close {
        display: block;
      }
    }

    .img {
      width: 80px;
      height: 80px;
      padding: 2px;
      border: 1px dashed #e2e2e2;
      background: #fff;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;

      .img-cover {
        display: block;
        width: 100%;
        height: 100%;
        background: no-repeat center center / 100%;
      }

      i {
        font-size: 32px;
      }
    }
    p.oneline-hide{
      width: 110px;
    }

    .img + div {
      flex: 1;
      div {
        display: flex;
        height: 28px;
        justify-content: flex-end;
        align-items: flex-end;
      }
    }
  }
}


.cropper-row {
  min-width: 540px;
}

.page-cropper {
  margin: auto;
  width: 500px;
  height: 800px;
  //border: 1px solid #ccc;
}

.node-crop {
  width: 200px;
  height: 100px;
  border: 1px solid #ccc;
  background-image: url();

  .node-crop-box {
    position: relative;
    overflow: hidden;
  }

  img {
    width: 500px;
    position: absolute;
  }
}


.not-crop-msg {
  color: #f31b1b;
  font-size: 14px;;
}

.node-btn {
  margin: 10px 0;
}

.audio-box {
  position: fixed;
  top: 0;
  z-index: 100;
  right: calc(4% + 9px);
}

.card-cropper /deep/ .ant-card-body {
  padding-left: 0;padding-right: 0;
}
</style>